<?php
// +----------------------------------------------------------------------
// | Author: derek <693472824@qq.com> <http://www.bloveambition.com/>
// +----------------------------------------------------------------------

namespace Blovex4\Controller;
use Blovex4\Logic\AdminLogic;
use Api\Logic\UserLogic;

/**
 * 小哥控制器
 * @author derek <693472824@qq.com>
 */
class WorkerController extends BaseController {

    /**
     * 获取小哥列表
     * @author derek <693472824@qq.com>
     */
    public function index () {
        
        $param = I('param');
        $siteID = I('site_id');
        
        $map = array();
        $available = AdminLogic::getSite();
        
        if(!empty($available) && $available > 0){
            $map['site_id'] = $available == $siteID ? $siteID : $available;
            
            //site_str 不为空，表示当前用户为站长（非超级管理员），站长只可查看正常状态的小哥
            //0:禁止登录；1：正常；2：闲散小哥新注册，等完善信息；3.闲散小哥已完善信息，待审核状态；
            //4：客服审核通过，已给闲散小哥发送短信通知，待培训状态（培训通过并修改所属站点后即变成 status = 1 正常状态；5.后台新增自有团队成员初始状态；
            $map['status'] = array('in', '1,5');     
            $siteList = M('Site')->where(array('site_id'=>$available))->getField('site_id,site_name,parent_id');
        }else{
            $siteList = M('Site')->getField('site_id,site_name,parent_id');
            
            if(!empty($siteID)){
                $map['site_id'] = $siteID;
            }
        }
        
        if(!empty($param)){
        
            $map['Worker.account|Worker.name'] = array('like', '%'.(string)$param.'%');
        }
        
        $view = D('WorkerSiteView');
        $list = $this->lists($view, $map, 'worker_id DESC');
        
        $this->assign('param', $param);
        $this->assign('list', $list);
        $this->assign('siteList', $siteList);
        $this->display();
    }

    /**
     * 增加小哥以及修改小哥
     *
     * @param integer $admin_id
     *            小哥ID.
     * @author derek <693472824@qq.com>
     */
    public function editAction() {
        
        $workerID = I('worker_id');
    
        if (!empty($workerID)) {
    
            $workerLogic = D('Worker', 'Logic');
            $workerModel = $workerLogic->getWorkerByID($workerID);
    
            if (empty($workerModel)) {
                $this->error('获取数据失败', U('index'));
            }else{
                
                $this->assign('workerModel', $workerModel);
            }
        }
        
        $available = AdminLogic::getSite();
        
        //当前用户可管理站点
        if(!empty($available)){
            $map['site_id'] = $available;
        }
        
        $siteList = M('Site')->where($map)->getField('site_id,site_name,address');
        $trainingList = D('Training', 'Logic')->getTrainingList();
    
        $this->assign('siteList', $siteList);
        $this->assign('trainingList', $trainingList);
        $this->assign('fileSize', C('UPLOAD_PICTURE_CONFIG.maxSize'));
        $this->display();
    }
    
    /**
     * 保存小哥信息
     *
     * @author derek <lixm@my818.com>
     */
    public function saveAction() {
    
        $workerLogic = D('Worker', 'Logic');
        $result = $workerLogic->saveAction();
    
        if ($result === false) {
            $this->error('操作失败' . $workerLogic->getError());
        } else {
            $this->success('操作成功', U('index'));
        }
    }

    /**
     * 小哥删除
     * @author derek <693472824@qq.com>
     */
    public function del() {
        
        $workerID = I('worker_id');
        
        if(empty($workerID)){
            $this->error('参数错误！');
        }
        
        $workerLogic = D('Worker', 'Logic');
        $result = $workerLogic->del($workerID);
        
        if ($result === false) {
            $this->error('参数错误', U('index'));
        } else if($result === '-1'){
            $this->error('操作失败，当前小哥有未处理订单，不允许删除', U('index'));
        }else{
            $this->success('操作成功！', U('index'));
        }
    }
    
    /**
     * 查询小哥信息
     */
    public function ajax_info(){
        
        $workerID = I('worker_id');
        $siteStr = AdminLogic::getSite();
        
        $map['worker_id'] = $workerID;
        
        if(!empty($siteStr)){
            $map['site_id'] = array('in', $siteStr);
        }
        
        $worker = M('Worker')->find($workerID);
        
        if(!empty($worker)){
            
            $result['status'] = '1';
            $result['info'] = $worker;
        }else{
            $result['status'] = '0';
        }
        
        $this->ajaxReturn($result);
    }
    
    /**
     * 提现、充值、上次现金
     */
    public function cash(){
        
        $opType = I('op_type');
        $cash = I('cash');
        $workerID = I('worker_id');
        $orderNo = I('order_no');
        
        if(empty($workerID) || !in_array($opType, array('1', '2', '5')) || empty($cash)){
            $this->error('参数错误');
        }elseif ($opType == '5' && empty($orderNo)){
            $this->error('参数错误');
        }
        
        $cashModel = M('WorkerCash');
        $workerModel = M('Worker');
        $worker = $workerModel->where(array('worker_id'=>$workerID))->find();
        
        if($opType == '1' && $cash > $worker['balance']){
            $this->error('提现金额不能大于账户余额');
        }
        
        if($opType == '1'){
            
            $result = $workerModel->where(array('worker_id'=>$workerID))->setDec('balance', $cash);
            
        }elseif ($opType == '2'){
            $result = $workerModel->where(array('worker_id'=>$workerID))->setInc('balance', $cash);
        }elseif ($opType == '5'){
            $order = M('Orders')->where(array('order_no'=>$orderNo, 'worker_id'=>$workerID))->find();
            
            if(empty($order)){
                $this->error('此订单号不属于该小哥，请确认后重新操作');
            }
            
            //该订单现金未上次
            $workCash = $cashModel->where(array('order_id'=>$order['order_id'], 'status'=>'2'))->find();
            
            if(empty($workCash) || $order['pay_type'] != '2'){
                $this->error('此订单不需上交现金，请确认后重新操作');
            }elseif ($order['rate_price'] != $cash){
                $this->error('此订单上交金额不正确，请确认后重新操作');
            }
            
            $proportion = C('TEAM_PROPORTION') ? : '80';
            $balance = round($order['turnover'] * $proportion/100, 2);
            $balance = $cash + $balance;
            $result = $workerModel->where(array('worker_id'=>$workerID))->setInc('balance', $balance);
        }
        
        if($result){
            $data['op_type'] = $opType;
            $data['worker_id'] = $workerID;
            $data['order_id'] = empty($order['order_id']) ? '0' : $order['order_id'];
            $data['previous'] = $worker['balance'];
            $data['cash'] = $cash;
            $data['balance'] = $opType == '1' ? $worker['balance'] - $cash : ($opType == '2' ? $worker['balance'] + $cash : $worker['balance'] + $balance);
            $data['status'] = '1';
            $data['create_time'] = NOW_TIME;
            $data['admin_id'] = AdminLogic::is_login();
            
            $cashModel->add($data);
            $cashModel->where(array('order_id'=>$order['order_id']))->setField('status', '1');      //现金已上交，避免重复上交
            
            $this->success('操作成功', U('index'));
        }else{
            $this->error('操作失败', U('index'));
        }
    }
    
    /**
     * 查看用户对小哥评价
     */
    public function evaluation(){
        
        $workerID = I('worker_id');
        
        $worker = M('Worker')->find($workerID);
        
        if(empty($worker)){
            $this->error('参数错误', U('index'));
        }
        
        $map['WorkerEvaluation.worker_id'] = $workerID;
        
        $view = D('EvaluationView');
        $list = $this->lists($view, $map, 'WorkerEvaluation.ev_id DESC');
        
        $this->assign('param', $param);
        $this->assign('list', $list);
        $this->display();
        
    }
    
    /**
     * 现金流水
     */
    public function cashFlow(){
        
        $workerID = I('worker_id');
        
        $map['WorkerCash.worker_id'] = $workerID;
        
        $view = D('CashView');
        $list = $this->lists($view, $map, 'WorkerCash.create_time DESC');
        
        $this->assign('list', $list);
        $this->display();
    }
}